package config

import (
	"fmt"

	"gopkg.in/ini.v1"
)

type Config struct {
	Redis struct {
		Url      string
		DB       string
		Password string
	}

	ElasticSearch struct {
		Url      string
		Username string
		Password string
	}

	ODPEngine struct {
		ClientListRequestSecond      int
		ClientOSInfoRequestSecond    int
		HardwareSummaryRequestSecond int
		ClientListRequestCycle       int64
	}

	PostgreSQL struct {
		Host     string
		Port     int64
		Username string
		Password string
		DBName   string
	}

	PlatForm struct {
		Url string
	}
}

var Cfg Config

func init() {
	Cfg = Config{}

	cfg, err := ini.Load("app.ini")
	if err != nil {
		panic("Fail to read file: " + err.Error())
	}

	esHost := cfg.Section("es").Key("host").String()
	esPort := cfg.Section("es").Key("port").String()
	Cfg.ElasticSearch.Username = cfg.Section("es").Key("username").String()
	Cfg.ElasticSearch.Password = cfg.Section("es").Key("password").String()
	Cfg.ElasticSearch.Url = fmt.Sprintf("http://%s:%s", esHost, esPort)

	redisHost := cfg.Section("redis").Key("host").String()
	redisPort := cfg.Section("redis").Key("port").String()
	Cfg.Redis.Password = cfg.Section("redis").Key("password").String()
	Cfg.Redis.DB = cfg.Section("redis").Key("db").String()
	Cfg.Redis.Url = fmt.Sprintf("%s:%s", redisHost, redisPort)

	if clientListRequestSecond, err := cfg.Section("odp_engine").Key("client_list_request_second").Int(); err != nil {
		panic(err)
	} else {
		Cfg.ODPEngine.ClientListRequestSecond = clientListRequestSecond
	}
	if clientOSInfoRequestSecond, err := cfg.Section("odp_engine").Key("client_osinfo_request_second").Int(); err != nil {
		panic(err)
	} else {
		Cfg.ODPEngine.ClientOSInfoRequestSecond = clientOSInfoRequestSecond
	}

	if hardwareSummaryRequestSecond, err := cfg.Section("odp_engine").Key("hardware_summary_request_second").Int(); err != nil {
		panic(err)
	} else {
		Cfg.ODPEngine.HardwareSummaryRequestSecond = hardwareSummaryRequestSecond
	}

	if clientListRequestCycle, err := cfg.Section("odp_engine").Key("client_list_request_cycle").Int64(); err != nil {
		panic(err)
	} else {
		Cfg.ODPEngine.ClientListRequestCycle = clientListRequestCycle
	}

	Cfg.PostgreSQL.Host = cfg.Section("pg").Key("host").String()
	Cfg.PostgreSQL.Username = cfg.Section("pg").Key("username").String()
	Cfg.PostgreSQL.Password = cfg.Section("pg").Key("password").String()
	Cfg.PostgreSQL.DBName = cfg.Section("pg").Key("dbname").String()

	if pgPort, err := cfg.Section("pg").Key("port").Int64(); err != nil {
		panic(err)
	} else {
		Cfg.PostgreSQL.Port = pgPort
	}

	phpPort := int64(0)
	if port, err := cfg.Section("platform").Key("port").Int64(); err != nil {
		panic(err)
	} else {
		phpPort = port
	}

	Cfg.PlatForm.Url = fmt.Sprintf("http://%s:%d", cfg.Section("platform").Key("host").String(), phpPort)
}
